package com.unicom.projt;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import com.unicom.projt.db.Account;
import com.unicom.projt.db.DB;
import com.unicom.projt.util.AlertDialogUtils;
import com.unicom.projt.util.CheckUtils;
import com.unicom.projt.util.HttpClientDownloadUtils;
import com.unicom.projt.util.ToastUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * Created by IntelliJ IDEA.
 * User: Lee
 * Date: 12-2-19
 * Time: 下午7:24
 */
public class InputPhoneNumberPage extends Activity implements View.OnClickListener {
    private Button mNextBtn;
    private EditText mPhoneNumber;
    private InputPhoneNumberController mController;
    private UpgradeController mUpgradeController;

    private ProgressDialog mDialog;
    private static final int DIALOG_PROGRESS = 101;
    private Handler mHandler;

    private static final int DOWN_UPDATE = 1;
    private static final int DOWN_OVER = 2;
    private static final int DOWN_FAILED = 3;
    private ProgressBar mProgress;
    private int progress;
    private boolean interceptFlag = false;
    private Dialog downloadDialog;
    private Thread downLoadThread;
    public String downloadUrl="";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.input_number);

        mNextBtn = (Button) this.findViewById(R.id.input_number_next_btn);
        mPhoneNumber = (EditText) this.findViewById(R.id.input_phone_number);
        mNextBtn.setOnClickListener(this);
        mHandler=new Handler(){
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case DOWN_UPDATE:
                        mProgress.setProgress(progress);
                        break;
                    case DOWN_OVER:
                        downloadDialog.dismiss();
                        updateApk();
                        break;
                    case DOWN_FAILED:
                        showUpgradeErrorInfo();
                        break;
                    default:
                        break;
                }
            };
        };
        mController = new InputPhoneNumberController(this);
        mUpgradeController= new UpgradeController(this);
        showDialog(DIALOG_PROGRESS);
        mUpgradeController.checkTheVersion();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.input_number_next_btn:
                doLogin();
                break;
        }
    }

    private void doLogin() {
        if (mPhoneNumber.getText().toString().trim().equals("")) {
            AlertDialogUtils.showConfirmDiaLog(this, "请输入手机号");
            return;
        } else {
            if (!CheckUtils.isMobileNo(mPhoneNumber.getText().toString().trim())) {
                AlertDialogUtils.showConfirmDiaLog(this, "请输入正确的手机号");
                return;
            }
            showDialog(DIALOG_PROGRESS);
            mController.checkPhoneNumberAndJumpToPage(mPhoneNumber.getText().toString().trim());
        }

    }

    public void showUpgradeDialog(){
        AlertDialogUtils.showYesNoDiaLog(this,"检测到新版本，是否升级?",new AlertDialogUtils.Executor() {
            @Override
            public void execute() {
//                upgradeApplication();
                showDownloadDialog();
            }
        });
    }

    private void showDownloadDialog(){
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("软件版本更新");
        final LayoutInflater inflater = LayoutInflater.from(this);
        View v = inflater.inflate(R.layout.progress, null);
        mProgress = (ProgressBar)v.findViewById(R.id.progress);
        builder.setView(v);
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                interceptFlag = true;
            }
        });
        downloadDialog = builder.create();
        downloadDialog.show();
        downloadApk();
    }

    private void updateApk() {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(new File(Environment
                .getExternalStorageDirectory(), Const.APK_NAME)),
                "application/vnd.android.package-archive");
        startActivity(intent);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ( keyCode == KeyEvent.KEYCODE_SEARCH||keyCode == KeyEvent.KEYCODE_MENU) {
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onBackPressed() {
        AlertDialogUtils.showYesNoDiaLog(this, "是否退出系统?", new AlertDialogUtils.Executor() {
            @Override
            public void execute() {
                clickBackBtn();
                finish();
            }
        });
    }

    private void clickBackBtn() {
        super.onBackPressed();
    }

    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
            case DIALOG_PROGRESS:
                mDialog = new ProgressDialog(InputPhoneNumberPage.this);
                mDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
                mDialog.setMessage("正在处理，请等待......");
                mDialog.setCancelable(false);
                mDialog.setOnKeyListener(new DialogInterface.OnKeyListener(){
                    public boolean onKey(DialogInterface dialog, int keyCode,KeyEvent event) {
                        if (keyCode == KeyEvent.KEYCODE_SEARCH) {
                            return true;
                        }
                        return false;
                    }
                });
                return mDialog;
            default:
                return null;
        }
    }

    public void hideProgressDialog() {
        if (mDialog != null) {
            removeDialog(DIALOG_PROGRESS);
        }
    }



    private Runnable mDownloadApkRunnable = new Runnable() {
        @Override
        public void run() {
            try {
                URL url = new URL(downloadUrl);
                HttpURLConnection conn = (HttpURLConnection)url.openConnection();
                conn.setConnectTimeout(5*1000);
                conn.connect();
                int length = conn.getContentLength();
                InputStream is = conn.getInputStream();

                File apkFile = new File(Const.FILE_DIR+Const.APK_NAME);
                FileOutputStream fos = new FileOutputStream(apkFile);
                int count = 0;
                byte buf[] = new byte[1024];
                do{
                    int numread = is.read(buf);
                    count += numread;
                    progress =(int)(((float)count / length) * 100);
                    //更新进度
                    mHandler.sendEmptyMessage(DOWN_UPDATE);
                    if(numread <= 0){
                        //下载完成通知安装
                        mHandler.sendEmptyMessage(DOWN_OVER);
                        break;
                    }
                    fos.write(buf,0,numread);
                }while(!interceptFlag);//点击取消就停止下载.
                fos.close();
                is.close();
            } catch (MalformedURLException e) {
                Log.e(Const.TAG,e.getLocalizedMessage());
                mHandler.sendEmptyMessage(DOWN_FAILED);
            } catch(IOException e){
                Log.e(Const.TAG,e.getLocalizedMessage());
                mHandler.sendEmptyMessage(DOWN_FAILED);
            }

        }
    };

    private void showUpgradeErrorInfo(){
        downloadDialog.dismiss();
        interceptFlag = true;
        ToastUtils.showMessage(this,"更新失败，请稍候重试");
    }

    /**
     * 下载apk
     */

    private void downloadApk(){
        downLoadThread = new Thread(mDownloadApkRunnable);
        downLoadThread.start();
    }

    public String getDownloadUrl() {
        return downloadUrl;
    }

    public void setDownloadUrl(String downloadUrl) {
        this.downloadUrl = downloadUrl;
    }
}
